package com.xiaomitest;

public class RainWater {
    public static void main(String[] args) {

    }

    public int trap(int[] height) {
        int[] array = height;
        if (array == null || array.length < 3) {
            return 0;
        }
        int rainWater = 0;
        int left = 0;
        int right = array.length - 1;
        int leftMaxHeight = array[0];
        int rightMaxHeight = array[array.length - 1];

        while (left < right) {
            // 从左向右
            if (array[left] < array[right]) {
                if (array[left] > leftMaxHeight) {
                    leftMaxHeight = array[left];
                } else {
                    rainWater += (leftMaxHeight - array[left]);
                }
                ++left;
            } else {
                if (array[right] > rightMaxHeight) {
                    rightMaxHeight = array[right];
                } else {
                    rainWater += (rightMaxHeight - array[right]);
                }
                // 从右向左
                --right;
            }
        }
        return rainWater;
    }


}
